import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const PointSchema = new mongoose.Schema({
    creatorId: String,
    score: Number, // 积分数
    desc: String, // 说明
    dayString: String, // 添加的日期，方便查询
    createTime: Number
});

PointSchema.methods.savePoint = function (point, cb) {
    const today = moment();
    point.dayString = today.format('YYYY-MM-DD');
    point.createTime = today.unix();
    this.model('point').insertMany([point], cb);
};

PointSchema.methods.getPoints = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const pointModel = this.model('point');
    pointModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        pointModel.find(leftQuery, { passwd: 0 }).skip((current - 1) * pageSize).limit(pageSize).exec((err, points) => cb(err, points, count, hasMore));
    });
};

PointSchema.methods.getAllPoints = function (query, cb) {
    this.model('point').find(query, { name: 1, _id: 0 }, cb);
};

PointSchema.methods.getPoint = function (query, cb) {
    this.model('point').findOne(query, cb);
};

PointSchema.methods.updatePoint = function (point, cb) {
    const _id = point._id;
    delete point._id;
    this.model('point').findOneAndUpdate({ _id }, { $set: point }, cb);
};

PointSchema.methods.removePoints = function (pointIds, cb) {
    this.model('point').remove({ _id: { $in: pointIds } }, cb);
};

export default db.model('point', PointSchema);